import Vue from "vue";
import common from "@/api/common";
import member from "@/api/member";
import SubscribeService from "@/api/subscribe";
import config_url from "@/utils/config";

// 验证是否企业认证通过
const isCert = async () => {
  return await common.getCustomer();
};

// 企业认证
const qyrz = async () => {
  const res = await member.authorizedPersonApply();
  if (res.status === 1) {
    if (res.data.companyId > 0) {
      return "1";
    }
    return "0";
  }
  return "0";
};
const fIsCustomer = async () => {
  return (await qyrz()) === "1";
};

const orderBtn = (type, name, detail) => {
  // type 1自营 2第三方
  // name 按钮类型 1购买证明 2购买备案证明 3经办人信息   4订单合同 5立即支付 6取消订单

  // status 订单状态        5  待提交 10待审核 20待确认 25  待确认合同 30已确认 -10已取消
  // payState 支付状态     -1 待支付 10待确认 20已通过 -10 未通过
  // payType                1 信用支付 2 银行转账 3 账期 + 转账 4 承兑汇票 5 承兑汇票 + 转账 6.小雨点 8-新链贷

  // console.log(type,name,detail)

  const {
    status,
    payState,
    payType,
    deliverType,
    driverCar,
    ncNo,
    saleType,
    payStatus,
    isDrug,
    approvalStatus,
    isSample,
    userType,
    isFlyCalculation
  } = detail;

  if (type == 1) {
    switch (name) {
      case 4: // 订单合同
        return ([25, 30].includes(status) || (isDrug === 1 && approvalStatus === 30 && [10].includes(status))) && isSample === 0 && userType === 1;

      case 5: // 收银台 提交按钮
        if (saleType == 20) return true;

        const reg5_1 = ![10, 20, -20].includes(payStatus) && [25, 30].includes(status);

        return reg5_1;

      case 6: // 取消订单
        return ([10, 20, 25].includes(status) || (userType === 2 && status === 30)) && [-1, -10].includes(payStatus) && [10].includes(payState);

      case 7:
        // 飞算订单不显示 立即支付入口
        if (isFlyCalculation) return false;
        // 立即支付 去到收银台的 入口
        // 样品
        if (detail.isSample == 1) {
          return [20, 25, 30].includes(status);
        }
        // 非金融
        if (![6, 8, 20].includes(payType * 1)) {
          return [25, 30].includes(status);
        }
        // 金融
        return [30].includes(status);
      // let res = detail.isSample == 1 ? [20, 25, 30].includes(status) : payType !== 8 ? [25, 30].includes(status) : [30].includes(status);
      // return res;
      case 8: // 申请售后
        return payState === 30 && [25, 30].includes(status);

      case 9: // 修改提货人
        return status !== -10 && deliverType === 2 && driverCar === "" && ncNo === "";
    }
  } else if (type == 2) {
    switch (name) {
      case 4: // 订单合同
        return false;
        // return [25, 30].includes(status) || (detail.saleDetailList && [2, 3].includes(detail.saleDetailList[0].type) && [10].includes(status));

      case 5: // 收银台 提交按钮
        if (saleType == 20) return true;

        const reg5_1 = ![10, 20, -20].includes(payStatus) && [25, 30].includes(status);

        return reg5_1;

      case 6: // 取消订单
        return [10, 20, 25].includes(status) && [-1, -10].includes(payStatus) && [10].includes(payState);

      case 7:
        // 飞算订单不显示 立即支付入口
        if (isFlyCalculation) return false;
        // 立即支付 去到收银台的 入口
        // return [25,30].includes(status)
        const res = detail.isSample == 1 ? [20, 25, 30].includes(status) : payType !== 8 ? [25, 30].includes(status) : [30].includes(status);
        return res;
      case 8: // 申请售后
        return payState === 30 && [25, 30].includes(status);

      case 9: // 修改提货人
        return status !== -10 && deliverType === 2 && driverCar === "" && ncNo === "";
    }
  }
};

// 是否显示按钮功能
const showFuncBtn = (type, detail) => {
  /**
   * orderStatus: 订单状态 --- 10：待提交 20：待修改 30：待审核 40：进行中 50：已完成 -10：已取消 -20：已关闭
   * isNeedContract: 是否需要上传合同 --- 0: 不需要 1：需要
   * contractStatus: 合同状态 --- 0：待上传 10：待审核 11：审核中 20：审核通过 30：审核驳回
   * confirmStatus: 确认订单状态 ---  10：待确认 20：已确认
   * payState: 支付状态 --- 10：未支付 20：	部分支付 30：	已支付
   * deliverNode:  发货节点 --- 10：款到发货 20：货到付款 30：货到票到付款
   * hasDeliver:  发货状态 --- 10 待发货 20 已发货 30 已签收
   * storeType: 店铺类型, 不等于1说明第三方
   */
  const {
    orderStatus,
    buttonsInfo,
    isSample,
    isNeedContract,
    payState,
    deliverType,
    driverCar,
    contractStatus,
    hasDeliver,
    confirmStatus,
    storeType
  } = detail;
  const funcArr = {
    orderDetailQuery: {
      name: "查看订单详情",
      remark: "待提交的订单无法查询",
      flag: orderStatus !== 10
    },
    orderContract: {
      name: "订单合同",
      code: 1,
      remark: "进行中、已完成订单，且需要合同",
      flag: isNeedContract === 1 && confirmStatus === 20 && [40, 50].includes(orderStatus)
    },
    orderPay: {
      name: "立即支付",
      code: 2,
      remark: "",
      flag: [40, 50, -20].includes(orderStatus) && [10, 20].includes(payState) && ((confirmStatus === 20 && isSample === 0) || isSample === 1)
    },
    orderPayDetail: {
      name: "支付信息",
      code: 3,
      remark: "",
      flag: [20, 30, 40].includes(orderStatus) && [30].includes(payState)
    },
    orderCancel: {
      name: "取消订单",
      code: 4,
      remark: "",
      flag:
        [20, 30, 40].includes(orderStatus) &&
        [10].includes(payState) &&
        [10].includes(hasDeliver) &&
        ((![20].includes(contractStatus) && [1].includes(isNeedContract)) || [0].includes(isNeedContract))
    },
    modifyDelivery: {
      name: "修改提货人",
      code: 5,
      flag: [20, 30, 40].includes(orderStatus) && deliverType === 2 && driverCar === "" && [10].includes(hasDeliver)
    },

    applyInvoice: {
      name: "申请开票",
      code: 6,
      flag: [40, 50, -20].includes(orderStatus) && [20].includes(contractStatus) && [30].includes(payState) && storeType === 1
    },
    showContract: {
      name: "查看合同",
      code: 9,
      remark: "第三方样品 且需要合同 且 已确认、未取消 ",
      flag: isNeedContract === 1 && confirmStatus === 20 && [40, 50].includes(orderStatus)
    },
    concatStore: {
      name: "联系商家",
      remark: "联系商家",
      code: 10
    }
  };
  if (!buttonsInfo) return false;
  const item = buttonsInfo.find((x) => x.code === funcArr[type].code);
  return item.visible;
};

const formatDecimal = (num, decimal) => {
  if (num) {
    num = num.toString();
    const index = num.indexOf(".");
    if (index !== -1) {
      num = num.substring(0, decimal + index + 2);
    } else {
      num = num.substring(0);
    }
    return parseFloat(num).toFixed(decimal);
  }
  return num;
};

const parsePrice = (num, unit) => {
  const str = String(num).split(".")[0];
  if (str.length >= 10) {
    return unit ? "亿" : formatDecimal(Number(str) / 100000000, 2);
  }
  if (str.length >= 5 && str.length < 10) {
    return unit ? "万" : formatDecimal(Number(str) / 10000, 2);
  }
  return unit ? "" : num;
};

const wxNavigatTo = (url) => {
  uni.navigateTo({ url });
};
// 返回顶部
const toTop = () => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 100
  });
};
// 是否数字
const isDigit = (value) => {
  return /^\d+$/.test(value);
};
/**
 * 判断是否是数值
 */
const isNumber = (value) => {
  return /^[-+]?\d+$/.test(value) || /^[-+]?\d+(\.\d+)?$/.test(value);
};

// 数组按数量拆分
const sliceArr = (arr, num) => {
  const newArr = [];
  for (let i = 0; i < arr.length; i += num) {
    newArr.push(arr.slice(i, i + num));
  }
  return newArr;
};

// 保留2位小数
const twoPoint = (value) => {
  let num = Math.round(parseFloat(value) * 100) / 100;
  const str = num.toString().split(".");
  if (str.length == 1) {
    num = `${num.toString()}.00`;
    return num;
  }
  if (str.length > 1) {
    if (str[1].length < 2) {
      num = `${num.toString()}0`;
    }
    return num;
  }
};

const arrFilter = (arr, id) => {
  // 数组去重 by 某个属性
  const map = new Map();
  const array = new Array();
  arr.forEach((item) => {
    if (map.has(item[id])) {
      map.set(item[id], true);
    } else {
      map.set(item[id], false);
      array.push(item);
    }
  });
  return array;
};

const isSameArea = (data) => {
  // 数组去重 by 某个属性
  let isSame = true;
  const belongArea = data[0].stockObj.belongArea;
  if (data.length > 1) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].stockObj && data[i].stockObj.warehouseId != "请选择") {
        console.log(data[i].stockObj.belongArea, belongArea);
        if (data[i].stockObj.belongArea != belongArea) {
          isSame = false;
          return isSame;
        }
        isSame = true;
      }
    }
    return isSame;
  }
  return isSame;
};

const gPrice = (price, unitName, item) => {
  if (price === -1) {
    return `<span class='price_r'> 
    <span class='f_s_10'>登录看价</span>
    </span>`;
    // <span class='f_s_10'>¥</span>
    // <span class='f_s_16 numberFont'>??</span>
    // <span class='f_s_10'>/${unitName}</span>
  }
  return `<span class='price_r numberFont'>  
    <span class='f_s_12 f_w_600'>${item.priceText}</span>
    </span>`;

  // if (item.saleType === 3 && !item.hasOwnProperty("activityId")) {
  //   return `<span class='price_r'>
  //   <span class='f_s_12 f_w_600'>${item.saleTypeName}</span>
  //   </span>`;
  // } else {
  //   return `<span class='price_r f_w_600'> <span class='f_s_10'>¥</span> <span class='f_s_16 numberFont'>${formatDecimal(price, 2)}</span><span class='f_s_10'>/${unitName}</span></span>`;
  // }
};

export function gLogin(price, item, loginQueryStr = "") {
  if (price === -1) {
    const pages = getCurrentPages();
    let currPage = null;
    if (pages.length) {
      // 获取当前页面的对象（上边所获得的数组中最后一项就是当前页面的对象）
      currPage = pages[pages.length - 1];
    }
    // 获取当前页面的路由
    const route = (currPage.route && `/${currPage.route}`) || "";
    console.log("route", route);

    // 获取当前页面的参数
    const query = currPage.options;
    // 参数处理
    let queryString = [];
    if (query) {
      Object.keys(query).forEach((key) => {
        queryString.push(`${key}=${query[key]}`);
      });
      queryString = queryString.length ? `?${queryString.join("&")}` : "";
    }
    console.log("queryString", queryString);

    uni.setStorageSync("previous-page-url", route + queryString);

    // 登录
    uni.navigateTo({
      url: `/pages-user/login/login${loginQueryStr}`
    });
  }
}

const gLogin2 = (price, item) => {
  if (price === -1) {
    uni.reLaunch({
      url: "/pages-user/login/login"
    });
  }
};

const gCopy = (value) => {
  wx.setClipboardData({
    // 准备复制的数据
    data: value,
    success(res) {
      uni.showToast({
        title: "复制成功",
        icon: "none"
      });
    }
  });
};
// 根据自定义对象或数组，从接口里取你想要的字段并返回一个对象
const setJson = (arr, object) => {
  const obj = {};
  switch (Object.prototype.toString.call(arr)) {
    case "[object Array]":
      arr.forEach((key) => {
        obj[key] = object[key];
      });
      return obj;
    case "[object Object]":
      Object.keys(arr).forEach((key) => {
        obj[key] = object[key];
      });
      return obj;
  }
};
// 公共跳转方法: this.toFreshPage(url,{a:1})
const toFreshPage = (url, query) => {
  let queryString = [];
  if (query) {
    Object.keys(query).forEach((key) => {
      queryString.push(`${key}=${query[key]}`);
    });
    queryString = `?${queryString.join("&")}`;
    uni.navigateTo({ url: url + queryString });
  } else {
    uni.navigateTo({ url });
  }
};

//
const numberToThousandth = (number, scale = 2) => {
  number = numFixed(number, scale);
  return `${number}`.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, "$1,");
};

export function numFixed(num, scale = 1) {
  num = parseFloat(num);
  if (typeof num !== "undefined" && !isNaN(num)) {
    num = num.toFixed(scale);
    return num;
  }
  return 0;
}

// 判断是否存在港澳台地区
export function isExit(id) {
  id = Number(id);
  return [810000, 820000, 710000].includes(id);
}

// 判断是否存在港澳台地区
export function showAddressModal(address, callback) {
  // uni.showToast({
  //   title: '收货地址为出口,暂无物流配送，只支持“自提”，请咨询客服！',
  //   icon: 'none',
  // });
  uni.showModal({
    title: "温馨提示",
    content: `您选择的收货地址为${address} ，暂无物流/送货/快递服务，只支持自提，详情请咨询客服！`,
    showCancel: false,
    success: callback
  });
}
export function gRouteConfirm(params = { isCart: 0, isSample: 0, isActivity }) {
  const url = `/pages-order/thirdparty/index?isCart=${params.isCart}&storeId=${params.storeId}&isSample=${params.isSample}`;
  console.log("gRouteConfirm", url, uni);
  // context.app.router.push({ path });
  uni.navigateTo({ url });
}

export async function requestSubscribeMessage({ messageType = "", businessId = "", businessName = "" }, templateIds) {
  // console.log("templateIds", templateIds);
  if (!templateIds || templateIds.length < 1) return;
  return new Promise((resolve, reject) => {
    wx.getSetting({
      withSubscriptions: true,
      success: (resStatus) => {
        if (resStatus.subscriptionsSetting.mainSwitch == true && templateIds && templateIds.length > 0) {
          wx.requestSubscribeMessage({
            tmplIds: templateIds,
            success: (res) => {
              if (res && res[templateIds[0]] === "accept") {
                sendMessage({ messageType, businessId, businessName });
              }
              resolve(res);
            },
            fail: (error) => {
              console.log("订阅失败", error);
              reject("订阅失败");
            }
          });
        }
      }
    });
  });
}
// export async function appletAuthorization({ messageType = "", businessId = "", businessName = "" }) {
//   let appletTypes = (messageType + "").split(",").map(i => parseInt(i));
//   const params = { appletTypes, terminalType: 2, businessId, businessName };
//   return new Promise((resolve, reject) => {
//     wx.login({
//       success: async ({ code }) => resolve(!!(await SubscribeService.appletAuthorization({ ...params, code })).data.flag),
//       fail: res => reject(new Error("网络错误")),
//     });
//   });
// }
export async function getTemplateInfo({ messageType = "", businessId = "", businessName = "" }) {
  const appletTypes = `${messageType}`.split(",").map((i) => parseInt(i));
  const params = { appletTypes, terminalType: 2, businessId, businessName };
  return new Promise((resolve, reject) => {
    wx.login({
      success: async ({ code }) => {
        const res = await SubscribeService.appletAuthorization({
          ...params,
          code
        });
        console.log("appletAuthorization 请求参数", { ...params, code });
        console.log("appletAuthorization 返回", res.data);
        resolve(res);
      },
      fail: (res) => reject(new Error("网络错误"))
    });
  });
}
export async function sendMessage({ messageType = "", businessId = "", businessName = "" }) {
  const appletTypes = `${messageType}`.split(",").map((i) => parseInt(i));
  const params = { appletTypes, terminalType: 2, businessId, businessName };
  return new Promise((resolve, reject) => {
    wx.login({
      success: async ({ code }) => {
        const res = await SubscribeService.message({ ...params, code });
        console.log("message 请求参数", { ...params, code });
        console.log("message 返回", res.data);
        resolve(res);
      },
      fail: (res) => reject(new Error("网络错误", res))
    });
  });
}

/** 用于调价通知和到货通知
 * 消息类型 appletTypes:1：调价通知 ， 2 到货， 3 采购信息已报价通知 4 派发优惠券通知 5 优惠券3天到期通知 6 抢购活动通知
 *业务编号 businessId ：商品sku_id/采购单号/活动id
 *业务名字 businessName：商品名字、活动名字等
 *终端值 terminalType: 1:PC、2:小程序、3:Android、4:IOS、5:H5
 * */

export async function gNotification({ messageType = "", businessId = "", businessName = "" }) {
  return new Promise(async (resolve, reject) => {
    const token = uni.getStorageSync("yl-token");
    if (!token) {
      gLogin(-1);
      reject(new Error("未登录"));
      return;
    }
    const messageTxt = {
      1: "该商品价格变动，您将收到手机推送消息以及短信通知",
      2: "该商品到货，您将收到手机推送消息以及短信通知"
    };
    const res = await getTemplateInfo({ messageType, businessId, businessName });
    if ([1, 2].includes(messageType * 1)) {
      uni.showModal({
        title: "订阅成功",
        content: messageTxt[messageType * 1],
        showCancel: false,
        confirmText: "知道了",
        success: async () => {
          if (res.data.flag) {
            await requestSubscribeMessage({ messageType, businessId, businessName }, res.data.templateId);
            console.log("1111");
          }
          resolve(res);
        }
      });
    } else {
      res.data.flag && (await requestSubscribeMessage({ messageType, businessId, businessName }, res.data.templateId));
      resolve();
    }
  });
}

const debounce = (func, { runNow = true, delay = 300, msg = "" } = {}) => {
  let timeout = null;
  return (...args) => {
    const context = this;
    if (timeout) {
      clearTimeout(timeout);
      if (msg) {
        uni.showToast({
          icon: "none",
          title: msg
        });
      }
    }

    if (runNow) {
      const isRunNow = !timeout;
      timeout = setTimeout(() => (timeout = null), delay);
      isRunNow && func.apply(context, args);
    } else {
      timeout = setTimeout(() => func.apply(context, args), delay);
    }
  };
};

// 小程序扫码多参数解析
const splitSceneParams = scene => {
  if (!scene || typeof scene !== "string") return {};
  return decodeURIComponent(scene)
    .split("&")
    .reduce((total, item) => {
      const [key, value] = item.split("=");
      total[key] = value;
      return total;
    }, {});
};

Vue.prototype.orderBtn = orderBtn;
Vue.prototype.showFuncBtn = showFuncBtn;

Vue.prototype.numInit = formatDecimal;
Vue.prototype.parsePrice = parsePrice;
Vue.prototype.config_url = config_url;
Vue.prototype.fGoTo = wxNavigatTo;
Vue.prototype.toTop = toTop;
Vue.prototype.isDigit = isDigit;
Vue.prototype.isNumber = isNumber;
Vue.prototype.sliceArr = sliceArr;
Vue.prototype.twoPoint = twoPoint;
Vue.prototype.isCert = isCert; // isCert
Vue.prototype.arrFilter = arrFilter;
Vue.prototype.isSameArea = isSameArea;
Vue.prototype.gPrice = gPrice;
Vue.prototype.gLogin = gLogin;
Vue.prototype.gLogin2 = gLogin2;
Vue.prototype.gCopy = gCopy;
Vue.prototype.setJson = setJson;
Vue.prototype.toFreshPage = toFreshPage;
Vue.prototype.numberToThousandth = numberToThousandth;
Vue.prototype.fIsCustomer = fIsCustomer;
Vue.prototype.gRouteConfirm = gRouteConfirm;
Vue.prototype.debounce = debounce;
Vue.prototype.gNotification = gNotification;
Vue.prototype.getTemplateInfo = getTemplateInfo;
Vue.prototype.requestSubscribeMessage = debounce(requestSubscribeMessage, {
  delay: 1000,
  msg: "请勿频繁点击"
});
Vue.prototype.splitSceneParams = splitSceneParams;
